<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :defaults.sync="showColumn"
               :permission="permissionList"
               :page.sync="page"
               :before-open="beforeOpen"
               @sortable-change="sortableChange"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @refresh-change="refreshChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @filter="filterChange"
               @sort-change="sortChange"               
               @on-load="onLoad">
     <template slot-scope="scope" slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.code_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot="menuRight">
        <el-button type="default" @click.stop="exportExcel" icon="el-icon-download" circle size="small"></el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="text"
                   size="small"
                   icon="el-icon-document-copy"
                   @click.stop="handleOpenDesign(scope.row)">配置表单
        </el-button>
      </template>
    </avue-crud>
    <!-- 动态表单配置页面 -->
    <el-drawer 
        :close-on-press-escape="false"
        :with-header="false"
        :visible.sync="drawerDialog"
        :before-close="handleClose"
        custom-class="demo-drawer"
        destroy-on-close
        ref="drawer"
        direction="rtl"
        size="100%"
        @close="closeDrawer"
        > 
        <avue-form-design :options="options"
              :aside-left-width="270"
              :aside-right-width="380"
              storage
              :form-id="formId"
              :form-json="formJsonData"
              :form-json-v1="formJsonDataV1" 
              @saveJson="handleSaveJson"
              @closeDesignDrawer="closeDesignDrawer"
              @submit="handleSubmit">
        </avue-form-design>
    </el-drawer>
    <!-- 历史记录 -->
    <updateHistory ref="historyRecord"></updateHistory>
  </basic-container>
</template>

<script>
import {exportSysDynamicFormExcel,saveOrUpdateSysDynamicForm,saveOrUpdateSysDynamicFormList,saveSysDynamicForm,deleteSysDynamicForm,querySysDynamicForm,querySysDynamicFormListPage,updateSysDynamicForm,deleteSysDynamicFormList} from '@/api/system/sysDynamicFormApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
import updateHistory from '../../components/history/update-history'
export default {
  components: {
    updateHistory
  },
  data() {
    return {
      drawerDialog: false,
      form: {},
      selectionList: [],
      loading: true, 
      showColumn: [],
      formJsonData: '',
      formJsonDataV1: '',
      formId: '',
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: true,
        viewBtn: true,
        delBtn: true,
        cancelBtn: true,
        printBtn:false,
        saveBtn: true,
        filterBtn:true,          
        menuWidth: 290,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        sortable: true,
        column: [
          {
            label: 'ID',
            prop: 'id', 
            type: 'input', 
            search: false,
            searchMmultiple: true,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 10,
            width:150,
            overHidden: true,
            display: false,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }]
          },
          {
            label: '业务类型',
            prop: 'bizType', 
            type: 'select', 
            search: true,
            searchMmultiple: true,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 10,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            },
            {
              max: 10,
              message: '内容长度不能超过10字符',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '业务名称',
            prop: 'bizName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 50,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            },
            {
              max: 50,
              message: '内容长度不能超过50字符',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '业务编码',
            prop: 'bizCode', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 30,
            overHidden: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            },
            {
              max: 30,
              message: '内容长度不能超过30字符',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '表单编码',
            prop: 'formCode', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            maxlength: 30,
            overHidden: true,
            tip: '定义好的表单编号,一个表单编码只能作用于一个表单',
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            },
            {
              max: 30,
              message: '内容长度不能超过30字符',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '流程表单标志',
            prop: 'isFlowFlag', 
            type: 'switch', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 5,
            sortable: false,
            hide: false,
            maxlength: 1,
            overHidden: true,
            value: '0',
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            },
            {
              max: 1,
              message: '内容长度不能超过1字符',
              trigger: 'blur'
            }],
            dicData:[
              {
                label: '否',
                value: '0'
              },
              {
                label: '是',
                value: '1'
              }
            ],
            change: ({value,column}) => {
              if(value == '0'){
                this.findObject(this.option.column, 'flowId').disabled = true;  
                this.findObject(this.option.column, 'flowBeginWay').disabled = true;  
              }
              else{
                this.findObject(this.option.column, 'flowId').disabled = false;
                this.findObject(this.option.column, 'flowBeginWay').disabled = false;
              }
            }
          },
          {
            label: '流程ID',
            prop: 'flowId', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 9,
            sortable: false,
            hide: true,
            maxlength: 20,
            overHidden: true,
            disabled: true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            },
            {
              max: 20,
              message: '内容长度不能超过20字符',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '流程开始方式',
            prop: 'flowBeginWay', 
            type: 'radio', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 10,
            sortable: false,
            hide: true,
            maxlength: 30,
            overHidden: true,
            disabled: true,
            value: '0',
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            },
            {
              max: 30,
              message: '内容长度不能超过30字符',
              trigger: 'blur'
            }],
            dicData:[
              {
                label: '手工启动',
                value: '0'
              },
              {
                label: '自动启动',
                value: '1'
              }
            ]
          },
        ]
      },
      data: [],
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['userInfo','permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.code_add, true),
        viewBtn: this.vaildData(this.permission.code_view, true),
        delBtn: this.vaildData(this.permission.code_delete, true),
        editBtn: this.vaildData(this.permission.code_edit, true)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: { 
    //加载列表数据
    onLoad(page) {
      this.loading = true;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      querySysDynamicFormListPage(this.commonData).then(res => {
        
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 新增记录
     */
    rowSave(row, done, loading) {
      row.formJson = '{"column":[]}'
      row.formJsonV1 = '{"column":[]}'
      row.formJsonV2 = '{"column":[]}'
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      saveSysDynamicForm(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 更新记录
     */
    rowUpdate(row, index, done, loading) { 
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      updateSysDynamicForm(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteSysDynamicForm(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }); 
    },

    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteSysDynamicFormList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    
    /**
     * 打开编辑、查询弹窗前查询记录
     */
    beforeOpen(done, type) {
      this.reqParams =  {
        singleBody: {
          id:this.form.id
        }
      }
      let commonData = reqCommonMsg(this.reqParams)
      if (['edit', 'view'].includes(type)) {
        querySysDynamicForm(commonData).then(res => {
          this.form = res.data.body.singleBody;
        });
      }
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      //this.$console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportSysDynamicFormExcel(this.commonData);
    },
    // 打开设计弹框
    handleOpenDesign(row){
      //this.$console.log('row = ',row)
      this.currentRow = row;
      this.drawerDialog = true;
      this.formId = row.id;
      // 加上时间戳，每次打开的时候获取最新的变量
      this.formJsonData =  row.formJson +'||'+ new Date().getTime();
      this.formJsonDataV1 = row.formJsonV1
    },
    /**
     * 保存表单JSON
     */
    handleSaveJson(val) {
      this.loading = true;
      this.currentRow.formJsonV2 = this.currentRow.formJsonV1
      this.currentRow.formJsonV1 = this.currentRow.formJson
      this.currentRow.formJson = JSON.stringify(val);
      this.reqParams.singleBody = this.currentRow;
      this.commonData = reqCommonMsg(this.reqParams)
      updateSysDynamicForm(this.commonData).then(res => {
        this.singleBody={}
        this.currentRow = res.data.body.singleBody;
        this.formJsonData =  res.data.body.singleBody.formJson +'||'+ new Date().getTime();
        this.formJsonDataV1 = res.data.body.singleBody.formJsonV1
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '保存成功!'
        });
        this.loading = false;
      }, error => {
        //this.$console.log(error);
        this.loading = false;
      });
      //alert('测试按钮'+JSON.stringify(val));
    },
    closeDesignDrawer(val) {
      this.drawerDialog = false;
    },
    closeDrawer(){
      this.singleBody.tableName = null
      this.columnData = [];
      this.orderRules = [];
    },
    /**
     * 获取业务字典参数
     */
    async getBizDict() {
      let dicData = await this.$params.getBizDict('["dynamicBizType"]');
      this.findObject(this.option.column, 'bizType').dicData = dicData.dynamicBizType;
      //如果用了流程 需要做表单切换,此处将赋值好字典的表单做备份
      if(this.isFlow){
        this.optionTmp = this.deepClone(this.option);
      }
    }
  },
  created() {
    this.showColumn = this.$getStore({name:  this.userInfo.userId +'sysDynamicFormColumn'});
    // 获取业务字典
    setTimeout(() => {
      this.getBizDict();
    }, 1000);
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'sysDynamicFormColumn', content: this.showColumn});
      },
      deep: true
      //this.$setStore({name: this.userInfo.userId +'sysDynamicFormColumn', content: this.showColumn});
    }
  }
};
</script>
